import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:playtruly/common/models/index.dart';

import 'index.dart';

class UserHistoryActivitePage extends GetView<UserHistoryActiviteController> {
  const UserHistoryActivitePage({super.key});

  // 主视图
  Widget _buildView() {
    return SafeArea(
      child: Column(
        children: [
          // 日期选择器
          _buildDateSelector(),
          // 历史记录列表
          Expanded(
            child: Obx(() {
              // 显示加载状态
              if (controller.isLoading.value) {
                return const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                      SizedBox(height: 16),
                      Text(
                        "加载历史记录中...",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                );
              }
              
              // 显示错误信息
              if (controller.errorMessage.value.isNotEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.error_outline,
                        color: Colors.white,
                        size: 48,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        controller.errorMessage.value,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: controller.refreshData,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          foregroundColor: const Color(0xFFD94841),
                        ),
                        child: const Text("重试"),
                      ),
                    ],
                  ),
                );
              }
              
              // 显示历史记录列表
              if (controller.historyItems.isEmpty) {
                return const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.inbox_outlined,
                        color: Colors.white,
                        size: 48,
                      ),
                      SizedBox(height: 16),
                      Text(
                        "暂无历史记录",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                );
              }
              
              return RefreshIndicator(
                onRefresh: () async => controller.refreshData(),
                color: Colors.white,
                backgroundColor: const Color(0xFFD94841),
                child: ListView.builder(
                  padding: const EdgeInsets.fromLTRB(12, 8, 12, 16),
                  itemCount: controller.historyItems.length,
                  itemBuilder: (context, index) {
                    final item = controller.historyItems[index];
                    return _buildHistoryItem(item);
                  },
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  // 构建日期选择器
  Widget _buildDateSelector() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.2),
        borderRadius: BorderRadius.circular(25),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Obx(() => GestureDetector(
            onTap: _showDatePicker,
            child: Row(
              children: [
                Text(
                  controller.formattedDate,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(width: 8),
                const Icon(
                  Icons.keyboard_arrow_down,
                  color: Colors.white,
                  size: 20,
                ),
              ],
            ),
          )),
          const Text(
            "(按日期查询历史记录)",
            style: TextStyle(
              color: Colors.white70,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  // 显示日期选择器
  void _showDatePicker() async {
    final selectedDate = await showDatePicker(
      context: Get.context!,
      initialDate: controller.selectedDate.value,
      firstDate: DateTime(2020), // 可以查询的最早日期
      lastDate: DateTime.now(), // 最晚日期为今天
      locale: const Locale('zh', 'CN'), // 设置为中文
      helpText: '选择日期',
      cancelText: '取消',
      confirmText: '确定',
      fieldHintText: 'YYYY/MM/DD',
      fieldLabelText: '输入日期',
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: const Color(0xFFD94841), // 主色调
              onPrimary: Colors.white, // 主色调上的文字颜色
              surface: Colors.white, // 表面颜色
              onSurface: Colors.black, // 表面上的文字颜色
            ),
          ),
          child: child!,
        );
      },
    );

    if (selectedDate != null) {
      controller.updateSelectedDate(selectedDate);
    }
  }

  // 构建历史记录项 - 重新设计更紧凑美观的UI
  Widget _buildHistoryItem(HistoryItemData item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.06),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          // 🔥 顶部发布者信息条
          Container(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
            child: Row(
              children: [
                // 发布者头像
                ClipRRect(
                  borderRadius: BorderRadius.circular(18),
                  child: CachedNetworkImage(
                    imageUrl: item.publisherAvatar?.isNotEmpty == true 
                        ? item.publisherAvatar! 
                        : 'https://via.placeholder.com/36x36.png?text=${item.publisherNickname?.substring(0, 1) ?? "U"}',
                    width: 36,
                    height: 36,
                    fit: BoxFit.cover,
                    errorWidget: (context, url, error) {
                      return Container(
                        width: 36,
                        height: 36,
                        decoration: BoxDecoration(
                          color: const Color(0xFFD94841),
                          borderRadius: BorderRadius.circular(18),
                        ),
                        child: Center(
                          child: Text(
                            item.publisherNickname?.substring(0, 1).toUpperCase() ?? 'U',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                const SizedBox(width: 12),
                // 发布者信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            item.publisherNickname ?? '未知用户',
                            style: const TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                          ),
                          const SizedBox(width: 8),
                          // 类型标签
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: _getTypeColor(item.type ?? 'unknown'),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              _getTypeDisplayName(item.type ?? 'unknown'),
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 10,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ],
                      ),
                      if (item.publishTime != null)
                        Text(
                          _formatTime(item.publishTime!),
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                    ],
                  ),
                ),
                // 分类标签（右侧）
                if (item.category != null && item.category!.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.orange[50],
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.orange[200]!),
                    ),
                    child: Text(
                      item.category!.first,
                      style: TextStyle(
                        color: Colors.orange[700],
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
              ],
            ),
          ),
          
          // 🔥 主要内容区域
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题（增大字号，增强视觉重点）
                if (item.title != null && item.title!.isNotEmpty)
                  Text(
                    item.title!,
                    style: const TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                      height: 1.3,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                
                // 内容描述
                if (item.content != null && item.content!.isNotEmpty && item.content != item.title) ...[
                  const SizedBox(height: 6),
                  Text(
                    item.content!,
                    style: TextStyle(
                      color: Colors.grey[700],
                      fontSize: 14,
                      height: 1.4,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
                
                const SizedBox(height: 8),
                
                // 🔥 图片展示（优化布局，最多显示4张）
                if (item.images != null && item.images!.isNotEmpty) ...[
                  SizedBox(
                    height: 70,
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: item.images!.length > 4 ? 4 : item.images!.length,
                      itemBuilder: (context, imageIndex) {
                        return Container(
                          margin: const EdgeInsets.only(right: 6),
                          child: Stack(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: CachedNetworkImage(
                                  imageUrl: item.images![imageIndex],
                                  width: 70,
                                  height: 70,
                                  fit: BoxFit.cover,
                                  errorWidget: (context, url, error) {
                                    return Container(
                                      width: 70,
                                      height: 70,
                                      decoration: BoxDecoration(
                                        color: Colors.grey[200],
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      child: const Icon(
                                        Icons.broken_image,
                                        color: Colors.grey,
                                        size: 20,
                                      ),
                                    );
                                  },
                                ),
                              ),
                              // 如果是最后一张且还有更多图片，显示数量提示
                              if (imageIndex == 3 && item.images!.length > 4)
                                Container(
                                  width: 70,
                                  height: 70,
                                  decoration: BoxDecoration(
                                    color: Colors.black.withValues(alpha: 0.5),
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: Center(
                                    child: Text(
                                      '+${item.images!.length - 4}',
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontSize: 14,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                  const SizedBox(height: 8),
                ],
                
                // 🔥 底部信息栏（地点 + 统计信息）
                Row(
                  children: [
                    // 地点信息
                    if (item.location != null && item.location!.isNotEmpty) ...[
                      Icon(Icons.location_on, size: 14, color: Colors.grey[500]),
                      const SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          item.location!,
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                    
                    // 统计信息
                    if (item.isActivity && item.participantCount != null) ...[
                      const SizedBox(width: 12),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                        decoration: BoxDecoration(
                          color: Colors.blue[50],
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.people, size: 12, color: Colors.blue[600]),
                            const SizedBox(width: 4),
                            Text(
                              '${item.participantCount}${item.maxParticipants != null ? '/${item.maxParticipants}' : ''}',
                              style: TextStyle(
                                color: Colors.blue[700],
                                fontSize: 11,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    
                    if (item.isComment && item.likeCount != null) ...[
                      const SizedBox(width: 12),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.thumb_up, size: 12, color: Colors.red[400]),
                          const SizedBox(width: 4),
                          Text(
                            '${item.likeCount}',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 11,
                            ),
                          ),
                          if (item.commentCount != null) ...[
                            const SizedBox(width: 8),
                            Icon(Icons.comment, size: 12, color: Colors.grey[500]),
                            const SizedBox(width: 4),
                            Text(
                              '${item.commentCount}',
                              style: TextStyle(
                                color: Colors.grey[600],
                                fontSize: 11,
                              ),
                            ),
                          ],
                        ],
                      ),
                    ],
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 获取类型颜色
  Color _getTypeColor(String type) {
    switch (type) {
      case 'activity':
        return const Color(0xFFD94841); // 红色表示活动
      case 'comment':
        return Colors.blue; // 蓝色表示评论
      default:
        return Colors.grey; // 灰色表示未知类型
    }
  }

  // 获取类型显示名称
  String _getTypeDisplayName(String type) {
    switch (type) {
      case 'activity':
        return '活动';
      case 'comment':
        return '评论';
      default:
        return '未知';
    }
  }

  // 格式化时间显示
  String _formatTime(String timeString) {
    try {
      final dateTime = DateTime.parse(timeString);
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
          '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } catch (e) {
      return timeString; // 如果解析失败，返回原始字符串
    }
  }



  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserHistoryActiviteController>(
      init: UserHistoryActiviteController(),
      id: "user_history_activite",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFD94841),
          extendBodyBehindAppBar: true,
          appBar: AppBar(
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
              onPressed: () => Get.back(),
            ), 
            title: const Text(
              "历史记录",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            backgroundColor: Colors.transparent,
            elevation: 0,
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.light,
            ),
          ),
          body: _buildView(),
        );
      },
    );
  }
}
